<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="searchForm" :model="searchForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="库名称">
              <el-input
                v-model="searchForm.warehouseName"
                placeholder="请输入库名称"
              />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="6">
            <el-button
              icon="iconfont iconxianxing_sousuo"
              type="primary"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              icon="iconfont iconxianxing_zhongzhi"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-col>
          <el-col :span="24" class="text-left">
            <el-button type="primary" @click="onAdd">
              新增库
            </el-button>
            <el-button type="warning" @click="onDownLoad">
              下载商家模板
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table
        ref="table"
        :current-page="page"
        :header-data="tableHeader"
        :index="false"
        :loading="loading"
        :page-size="limit"
        :table-data="tableData"
        :total="total"
        class="data-table"
        style="width: 100%"
        border
        @now-page="handlePage"
        @now-size="handleSize"
        @table-sort="handleSort"
      />
    </el-main>
    <el-drawer :title="title" :visible.sync="drawerVisible">
      <div class="drawer-main">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="top"
          label-width="80px"
        >
          <el-form-item label="库名称" prop="warehouseName">
            <el-input v-model="form.warehouseName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="type !== 'look'" class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
          <el-button @click="onCancel"> 取消</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      v-loading="fileLoading"
      title="上传文件"
      :visible.sync="dialogTableVisible"
      width="600px"
      element-loading-text="上传中……"
      element-loading-spinner="el-icon-loading"
    >
      <el-upload
        class="upload-demo"
        action="/api/warehouse/uploadExcel"
        accept=".xlsx,.xls"
        :data="uploadData"
        :headers="headerToken"
        :before-upload="beforeAvatarUpload"
        :on-progress="avatarProgress"
        :on-success="uploadSuccess"
        :limit="1"
        drag
        :multiple="false"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          只能上传.xlsx，.xls文件，且不超过1M
        </div>
      </el-upload>
    </el-dialog>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getWarehouseList,
  postWarehouseDel,
  postWarehouseAdd,
  postWarehouseUpdate,
  getWarehouseExcel,
} from "./api";
import { parseTime } from "@/utils";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
export default {
  name: "WarehouseList",
  mixins: [addTable],
  data() {
    return {
      searchForm: {
        warehouseName: "",
      },
      fileLoading: false,
      dialogTableVisible: false,
      title: "",
      type: "look",
      tableHeader: [],
      drawerVisible: false,
      uploadData: {
        warehouseId: "",
        warehouseName: "",
      },
      form: {
        warehouseId: "",
        warehouseName: "",
        remark: "",
      },
      rules: {
        warehouseName: [{ required: true, message: "库名称必填" }],
      },
    };
  },
  computed: {
    headerToken() {
      return { authorization: getToken() };
    },
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.tableHeader = [
      {
        prop: "warehouseName",
        label: "库名称",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "remark",
        label: "备注",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "createdTime",
        label: "创建时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = vm.createdTime ? parseTime(vm.createdTime) : "";
          return <span>{time}</span>;
        },
      },
      {
        width: 200,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          const arr = [];
          const isAdmin = this.userInfo.role === "1";
          if (isAdmin) {
            arr.push(
              {
                text: "编辑",
                type: "text",
                event: this.onEdit,
              },
              {
                text: "删除",
                type: "text",
                event: this.onDelete,
              },
              {
                text: "导入商家",
                type: "text",
                event: this.onAddExel,
              }
            );
          } else {
            arr.push(
              {
                text: "编辑",
                type: "text",
                event: this.onEdit,
              },
              {
                text: "导入商家",
                type: "text",
                event: this.onAddExel,
              }
            );
          }
          return arr;
        },
      },
    ];
    this.getTableData();
  },

  methods: {
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 1MB!");
      }
      return isLt1M;
    },
    avatarProgress() {
      this.fileLoading = true;
    },
    uploadSuccess({ success, message }) {
      if (success) {
        this.$message.success(message);
        this.fileLoading = false;
      } else {
        this.$message.error(message);
        this.fileLoading = false;
      }
      this.dialogTableVisible = false;
    },
    onAddExel(row) {
      this.uploadData.warehouseId = row.warehouseId;
      this.uploadData.warehouseName = row.warehouseName;
      this.dialogTableVisible = true;
    },
    async onDownLoad() {
      const res = await getWarehouseExcel();
      const url = window.URL.createObjectURL(new Blob([res]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "商家模板.xlsx");
      document.body.appendChild(link);
      link.click();
    },
    onEdit(row) {
      this.form = {
        ...row,
      };
      this.type = "edit";
      this.title = "编辑库";
      this.drawerVisible = true;
    },
    onAdd() {
      this.form = {};
      this.type = "add";
      this.title = "新增库";
      this.drawerVisible = true;
    },
    onDelete(row) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        postWarehouseDel({ warehouseId: row.warehouseId })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.getTableData();
          })
          .catch();
      });
    },
    getTableData() {
      this.loading = true;
      this.getTableParams();
      getWarehouseList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data, pageInfo } = res;
          setTimeout(() => {
            this.loading = false;
            this.tableData = data;
            this.total = pageInfo.total;
          }, 500);
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.warehouseId
            ? postWarehouseUpdate(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.drawerVisible = false;
                this.form = {};
                this.getTableData();
              })
            : postWarehouseAdd(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.drawerVisible = false;
                this.form = {};
                this.getTableData();
              });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onCancel() {
      this.drawerVisible = false;
      this.$refs.form.resetFields();
    },
  },
};
</script>
<style lang="scss">
.upload-demo {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-upload-dragger {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
